//
//  SendEmailToOwnerView.swift
//  ezyform
//
//  Created by MoennigQ on 26/3/20.
//  Copyright © 2020 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
class SendEmailToOwnerView: GreenNaviBarView {
    private lazy var disposeBag = DisposeBag()
    let nameTextfield = TextFieldWithRequiredView()
    let emailTextfield = TextFieldWithRequiredView(.email)
    
    let countDownLabel = BaseLabel()
    let sendBtn = OperationButton(R.string.localizable.send())
    @objc dynamic var countDownSeconds: Int = 0
    var emailKey: String = ""
    var ownerNameKey: String = ""
    
    override func setUpView() {
        let scrollView = DIYScrollView()
        scrollView.drawCorner(byRoundingCorners: [.topLeft,.topRight],radii: 16)
        scrollView.backgroundColor = .white
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(topBackView.snp.bottom).offset(-20)
            make.left.right.equalTo(self)
            make.bottom.equalToSuperview()
        }
        let contentBackView = UIView()
        contentBackView.backgroundColor = .white
        scrollView.addSubview(contentBackView)
        
        contentBackView.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(scrollView)
            make.left.right.equalTo(self)
            make.height.equalTo(scrollView)
        }
        let tipLabel = ContentLabel(hexStr: "#292D3299")
        tipLabel.text = R.string.localizable.sendOwnerAnEmailWithALinkToGetOwnerSSignature()
        tipLabel.textAlignment = .center
        tipLabel.numberOfLines = 0
        contentBackView.addSubview(tipLabel)
        tipLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(40)
            make.right.equalToSuperview().offset(-40)
            make.height.greaterThanOrEqualTo(0)
        }
        
        let showImageView = UIImageView(image: R.image.send_email_to_owner_sence())
        showImageView.setContentHuggingPriority(.defaultLow, for: NSLayoutConstraint.Axis.vertical)
        showImageView.setContentCompressionResistancePriority(.defaultLow, for: NSLayoutConstraint.Axis.vertical)
        showImageView.contentMode = .scaleAspectFit
        contentBackView.addSubview(showImageView)
        showImageView.snp.makeConstraints { (make) in
            make.top.equalTo(tipLabel.snp.bottom).offset(25)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.lessThanOrEqualTo(320)
        }
        
        //owner email title
        let ownerEmailTitle  = LabelWithRedStarView(R.string.localizable.ownerEmail())
        //
        contentBackView.addSubview(ownerEmailTitle)
        ownerEmailTitle.snp.makeConstraints { (make) in
            make.top.equalTo(showImageView.snp.bottom).offset(20)
            make.left.equalTo(16)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //email text field
        contentBackView.addSubview(emailTextfield)
        emailTextfield.snp.makeConstraints { (make) in
            make.top.equalTo(ownerEmailTitle.snp.bottom).offset(12)
            make.left.equalTo(ownerEmailTitle)
            make.right.equalTo(-16)
            make.height.greaterThanOrEqualTo(0)
        }
        //owner name title
        let ownerNameTitle  = LabelWithRedStarView(R.string.localizable.ownerName())
        //
        contentBackView.addSubview(ownerNameTitle)
        ownerNameTitle.snp.makeConstraints { (make) in
            make.top.equalTo(emailTextfield.snp.bottom).offset(20)
            make.left.equalTo(ownerEmailTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //owner name textview
        contentBackView.addSubview(nameTextfield)
        nameTextfield.snp.makeConstraints { (make) in
            make.top.equalTo(ownerNameTitle.snp.bottom).offset(12)
            make.left.right.equalTo(emailTextfield)
            make.height.greaterThanOrEqualTo(0)
        }
        countDownLabel.numberOfLines = 0
        countDownLabel.textAlignment = .center
        contentBackView.addSubview(countDownLabel)
        countDownLabel.snp.makeConstraints { (make) in
            make.top.equalTo(nameTextfield.snp.bottom).offset(16)
            make.left.right.equalTo(emailTextfield)
            make.height.greaterThanOrEqualTo(0)
        }
        
        contentBackView.addSubview(sendBtn)
        sendBtn.snp.makeConstraints { (make) in
            make.top.greaterThanOrEqualTo(countDownLabel.snp.bottom)
            make.bottom.equalTo(OperationButton.bottomMargin)
            make.left.right.equalTo(emailTextfield)
            make.height.equalTo(OperationButton.height)
        }
    }
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //
        let emailValid = self.emailTextfield.textField.rx.observe(String.self, "text").map({Tool().isValidEmail(emailStr: ($0 ?? ""))}).share(replay: 1)
        let nameValid = self.nameTextfield.textField.rx.observe(String.self, "text").map({($0 ?? "").count > 0 || self.countDownSeconds == 0}).share(replay: 1)
        let countDownSecondsValid = self.rx.observe(Int.self, "countDownSeconds").map({$0 == 0}).share(replay: 1)
        //合并
        let everythingValid = Observable.combineLatest(
            emailValid,
            nameValid,
            countDownSecondsValid
          ) { $0 && $1 && $2} // phoneValid和nameValid同时有效
          .share(replay: 1)

        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.sendBtn.enableBtn()
            }else{
                strongSelf.sendBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
    func setData(_ model: PVDDetailModel){
        self.emailTextfield.textField.text = model.owner_address.email
        self.nameTextfield.textField.text = model.signatures.owner_full_name
        //
        //MARK: 通过设置text属性则无法触发textField订阅事件,所以这里手动发送action
        self.emailTextfield.textField.sendActions(for: .allEditingEvents)
        self.nameTextfield.textField.sendActions(for: .allEditingEvents)
        //
        self.checkEverythingValid()
    }
    func refreshCountDown(){
        if self.countDownSeconds == 1 {
            self.sendBtn.setTitle(R.string.localizable.resend(), for: UIControl.State.normal)
            self.countDownLabel.text = ""
        }else{
            self.countDownSeconds = self.countDownSeconds - 1
            self.sendBtn.setTitle(R.string.localizable.resend(), for: UIControl.State.normal)
            //set counting down label
            let content1 = "\(self.countDownSeconds)"
            let content = R.string.localizable.pleaseWaitSBeforeResending(content1)//
            
            
            let range1 = (content as NSString).range(of:content1 )
            let attrString = NSMutableAttributedString(string: content)
            
            let attr: [NSMutableAttributedString.Key: Any] = [.font: R.font.interMedium(size: 14) as Any,.foregroundColor: UIColor(hexStr: "#292D3299")]
            let attr1: [NSMutableAttributedString.Key: Any] = [.font: R.font.interMedium(size: 14) as Any,.foregroundColor: UIColor(hexStr: "#379657")]
            
            attrString.addAttributes(attr, range: NSRange(location: 0, length: content.count))
            attrString.addAttributes(attr1, range: NSRange(location: range1.location, length: content1.count))
            self.countDownLabel.attributedText = attrString
        }
    }
    //只要发送过sms以后都是Resend按钮,且默认上次的信息
    func setResendInfo(){
        self.sendBtn.setTitle(R.string.localizable.resend(), for: UIControl.State.normal)
    }
    func setDefaultInfo(){
        //phone
        if let data = UserDefaults.standard.object(forKey: self.emailKey) as? String {
            self.emailTextfield.textField.text = data
            //MARK: 通过设置text属性则无法触发textField订阅事件,所以这里手动发送action
            self.emailTextfield.textField.sendActions(for: .allEditingEvents)
        }
        //name
        if let data = UserDefaults.standard.object(forKey: self.ownerNameKey) as? String {
            self.nameTextfield.textField.text = data
            //MARK: 通过设置text属性则无法触发textField订阅事件,所以这里手动发送action
            self.nameTextfield.textField.sendActions(for: .allEditingEvents)
        }
    }
}
